import { useState, useRef } from 'react';
import { useModel } from 'umi';
import { Space, Select } from 'antd';
import { useDeepCompareEffect } from '@ant-design/pro-utils';
import type { FC } from 'react';

type TValue = {
  province?: string;
  city?: string;
  area?: string;
};

type TProps = {
  width?: number;
  value?: TValue;
  onChange?: TAnyFunction;
};

const CommonCitySelect: FC<TProps> = (props) => {
  const { value, onChange, width = 120 } = props;
  const { initialState } = useModel('@@initialState');
  const { districtMap } = initialState || {};
  const provinceData = ((districtMap || [])[0] || {}).children || [];
  const [provinceMap] = useState<TCityApi.TCityItem[]>(provinceData);
  const [cityMap, setCityMap] = useState<TCityApi.TCityItem[]>([]);
  const [areaMap, setAreaMap] = useState<TCityApi.TCityItem[]>([]);
  const [currentProvince, setCurrentProvince] = useState<string | null>(value?.province || null);
  const [currentCity, setCurrentCity] = useState<string | null>(value?.city || null);
  const [currentArea, setCurrentArea] = useState<string | null>(value?.area || null);
  const isFirst = useRef(true);

  const triggerChange = (changedValue: { province?: string; city?: string; area?: string }) => {
    onChange?.({
      province: currentProvince,
      city: currentCity,
      area: currentArea,
      ...value,
      ...changedValue,
    });
  };

  const initData = (retProvince: TCityApi.TCityItem[] = provinceMap) => {
    if (value && isFirst.current) {
      isFirst.current = false;
      const { province, city, area } = value;
      const retCity = (retProvince.find((item) => item.id === province) || {}).children || [];
      setCityMap(retCity);
      setCurrentProvince(province as string);
      setCurrentCity(city as string);
      setCurrentArea(area as string);
      if (retCity && retCity.length) {
        const retArea = (retCity.find((item) => item.id === city) || {}).children || [];
        setAreaMap(retArea);
      }
    }
  };

  useDeepCompareEffect(() => {
    initData();
  }, [value]);

  const handleProvinceChange = (val: string) => {
    const retCity = (provinceMap.find((item) => item.id === val) || {}).children || [];
    setCityMap(retCity);
    setCurrentProvince(val);
    setCurrentArea(null);
    setCurrentCity(null);
    triggerChange({ province: val, city: '', area: '' });
  };

  const handleCityChange = (val: string) => {
    const retArea = (cityMap.find((item) => item.id === val) || {}).children || [];
    setAreaMap(retArea);
    setCurrentCity(val);
    setCurrentArea(null);
    triggerChange({ city: val, area: '' });
  };

  const handleAreaChange = (val: string) => {
    setCurrentArea(val);
    triggerChange({ area: val });
  };

  return (
    <Space>
      <Select
        value={currentProvince}
        style={{ width: `${width}px` }}
        onChange={handleProvinceChange}
        placeholder="省"
      >
        {provinceMap.map((item) => (
          <Select.Option key={item.id} value={item.id}>
            {item.name}
          </Select.Option>
        ))}
      </Select>
      <Select
        value={currentCity}
        style={{ width: `${width}px` }}
        onChange={handleCityChange}
        placeholder="市"
      >
        {cityMap.map((item) => (
          <Select.Option key={item.id} value={item.id}>
            {item.name}
          </Select.Option>
        ))}
      </Select>
      <Select
        value={currentArea}
        style={{ width: `${width}px` }}
        onChange={handleAreaChange}
        placeholder="区"
      >
        {areaMap.map((item) => (
          <Select.Option key={item.id} value={item.id}>
            {item.name}
          </Select.Option>
        ))}
      </Select>
    </Space>
  );
};

export default CommonCitySelect;
